/*
 * Copyright 2011 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.bize.knexions.android.knexion;

import java.util.HashMap;

import android.util.Log;

import nl.bize.knexions.android.AndroidKnexionsActivity;

/**
 * Utility class with static methods for managing Controller instances.
 * 
 * @author Joost A. Bloemsma
 */
public class ControllerFactory {
	private static final String TAG = "ControllerFactory";
	private static HashMap<String, Controller> controllers = new HashMap<String, Controller>();
	
	/**
	 * Returns the specified controller as a singleton.
	 * @param controllerClassName
	 * @param androidKnexionsActivity
	 * @return Gets the {@link Controller} instance for the requested Knexion
	 */
	@SuppressWarnings("unchecked")
	public static Controller get(String controllerClassName, AndroidKnexionsActivity androidKnexionsActivity) {
		Controller c = null;
		if (controllers.containsKey(controllerClassName)) {
			c = controllers.get(controllerClassName);
		} else {
			Class<Controller> clz;
			try {
				clz = (Class<Controller>) Class.forName(controllerClassName);
				c = (Controller) clz.newInstance();
				c.init(androidKnexionsActivity);
			} catch (Exception e) {
				Log.e(TAG, "Error initiating " + controllerClassName, e);
				c = null;
			}
			
		}
		
		return c;
	}
}

